% by clq ylx
% 2021/6/12
%% added timing function 
%% passed test
function[best_is_pref,opt_profits_pref]=prop_pref(j_all,pref)
global I J CURRENT
addpath functions;
Line = j_all;
patient_number = sum(Line > 0); % equivalent to size(2)
genPoisson(patient_number);
genPIE(patient_number);
S_pref = zeros(I, J);
% Profit = zeros(patient_number, I); % For What?

init_time = ftimer(); % set main clock

best_is_pref = zeros(1, patient_number);
opt_profits_pref = zeros(1,patient_number);

for n = 1:patient_number
    
    j = Line(n);
    profits = zeros(1, I);
    for i = 1:I
        S_test = S_pref;
        S_test(i, j) = S_test(i, j) + 1; % Replace rim & rimS
        Q = findQ(S_test); 
        R = findR(Q);
        profits(i) = function_fQR(Q, R);
    end
%above is the same with proposed main without preference    

%% special part for proposed pref
    pref_temp=pref(n);%randomly deciding the preference
    if pref_temp==1
        profit_temp=max(profits(1:I/2));
        i=find(profits == profit_temp);
    else
        profit_temp=max(profits(I/2+1:end));
        i=find(profits == profit_temp);
    end               %assign to the best slot according to preference
    best_is_pref(n) = i;
    S_pref(i, j) = S_pref(i, j) + 1;
    Q = findQ(S_pref);
    R = findR(Q);
    opt_profits_pref(n) = profits(i);%find the optimal profit
    % fprintf("    Time = %.2f seconds \n\n", ftimer()-start_time);
end
    
fprintf("\n\n Totle Time = %.1f seconds \n", ftimer()-init_time);
display(S_pref)
display(best_is_pref)

% plot(1:patient_number,sum_profits);
%showTimer();